package com.sgb.kjwl.view.widget.manage;

import android.content.Context;
import android.text.method.ScrollingMovementMethod;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;

/**
 * 可滚动的textView 并解决NestedScrollView冲突
 */
public class ScrollTextView extends androidx.appcompat.widget.AppCompatTextView {
    private float lastScrollY = 0;

    public ScrollTextView(Context context) {
        this(context, null);
    }

    public ScrollTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ScrollTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setMovementMethod(ScrollingMovementMethod.getInstance());
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (getLineCount() > getMaxLines()) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                lastScrollY = event.getRawY();
                Log.d("ScrollTextView", "down" + lastScrollY);
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                //滑动到头并且还在继续上滑动,或者滑动到底部就不要再拦截了(有误差)
                int sum = getLineHeight() * getLineCount() - getLineHeight() * getMaxLines();
                //计算上次与本次差
                float diff = lastScrollY - event.getRawY();
                if (diff > 0) {//下滑动并且到达了底部也不要处理了 //底部这里用abs的原因是,因为计算sum的时候有些误差
                    if (Math.abs(sum - getScrollY()) < 5) {
                        getParent().requestDisallowInterceptTouchEvent(false);
                    } else {
                        getParent().requestDisallowInterceptTouchEvent(true);
                    }
                } else if (diff < 0){//上滑动
                   if (getScrollY() == 0){//上滑到顶部不做处理
                       getParent().requestDisallowInterceptTouchEvent(false);
                   } else {
                       getParent().requestDisallowInterceptTouchEvent(true);
                   }
                }
                lastScrollY = event.getRawY();
                Log.d("ScrollTextView", "move" + lastScrollY);
            } else {
                getParent().requestDisallowInterceptTouchEvent(false);
            }
        }
        return super.onTouchEvent(event);
    }
}
